package com.his.system.manager.remote;

import com.alibaba.fastjson.JSONObject;
import com.his.system.manager.exception.BuzException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * RestTemplateUtils
 *
 * @Description
 * @Author Admin
 * @Date 2020-08-08 20:44:14
 */
@Slf4j
@Component
public class RestTemplateUtils {
    /**
     * jsonToMap
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> jsonToMap(JSONObject obj) {
        //map对象
        Map<String, Object> data = new HashMap<>();
        if (obj == null) {
            return data;
        }
        //循环转换
        Iterator it = obj.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            data.put(entry.getKey(), entry.getValue());
        }
        return data;
    }

    private RestTemplateUtils() {
    }

    public static JSONObject post(RestTemplate restTemplate, String url, Map params) {
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
        log.info("外部接口=====>请求[{}],请求参数[{}]", url, params.toString());
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        log.info("外部接口=====>响应[{}]", entity.getStatusCode());
        String body = entity.getBody();
        return JSONObject.parseObject(body);
    }

    public static JSONObject post(RestTemplate restTemplate, String url, String authorization, Map params) {

        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer " + authorization);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        log.info("外部接口=====>请求[{}],请求参数[{}]", url, params.toString());
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
        HttpStatus statusCode = response.getStatusCode();
        if (statusCode.value() != 200) {
            log.info("外部接口=====>响应[{}]", response.getBody());
            throw new BuzException(500);
        } else {
            return response.getBody();
        }
    }

    public static JSONObject get(RestTemplate restTemplate, String url, String authorization) {
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (StringUtils.isNotBlank(authorization)) {
            headers.add("Authorization", "Bearer " + authorization);
        }
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        HttpStatus statusCode = response.getStatusCode();
        if (statusCode.value() != 200) {
            throw new BuzException(500);
        } else {
            return response.getBody();
        }

    }

    public static JSONObject delete(RestTemplate restTemplate, String url, String authorization, Map params) {

        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer " + authorization);
//        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, JSONObject.class);
        HttpStatus statusCode = response.getStatusCode();
        if (statusCode.value() != 200) {
            throw new BuzException(500);
        } else {
            return response.getBody();
        }

    }

    public static JSONObject post(RestTemplate restTemplate, String url, HttpHeaders headers, Map params) {
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
        log.info("外部接口=====>请求[{}],请求参数[{}],请求header[{}]", url, params.toString(), headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        String body = entity.getBody();
        log.info("外部接口=====>响应[{}]", body);
        return JSONObject.parseObject(body);
    }

    public static JSONObject postBasic(RestTemplate restTemplate, String url, String authorization, HttpHeaders headers, Map params) {
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer " + authorization);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
        log.info("外部接口=====>请求[{}],请求参数[{}],请求header[{}]", url, params.toString(), headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        String body = entity.getBody();
        log.info("外部接口=====>响应[{}]", body);
        return JSONObject.parseObject(body);
    }

    public static JSONObject getAuth(RestTemplate restTemplate, String authorization, String url) {
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });
        HttpHeaders headers = new HttpHeaders();
        headers.put("Content-Type", Collections.singletonList("application/json;charset=UTF-8"));
        headers.add("Authorization", authorization);
        log.info("外部接口=====>请求[{}],请求header[{}]", url, headers);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        log.info("外部接口=====>响应[{}]", response.toString());
        HttpStatus statusCode = response.getStatusCode();
        if (statusCode.value() != 200) {
            throw new BuzException(500);
        } else {
            return response.getBody();
        }
    }
}
